﻿using System;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Timers;
using System.Net;
using System.Collections.Concurrent;

namespace WebSocketServer.Managers
{
    public class EmailManager
    {
        public ConcurrentQueue<MailMessage> MailQueue { get; set; }
        private Timer _sendMailTimer;
        public EmailManager()
        {
            MailQueue = new ConcurrentQueue<MailMessage>();
            _sendMailTimer = new Timer()
            {
                Interval = 2000,
                AutoReset = false,
            };
            _sendMailTimer.Elapsed += _sendMailTimer_Elapsed;
        }

        void _sendMailTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _sendMailTimer.Enabled = false;
            try
            {
                string fromPassword = System.Configuration.ConfigurationManager.AppSettings["EmailPassword"];
                string senderEmail = System.Configuration.ConfigurationManager.AppSettings["EmailAddress"];
                //  string subject = "Subject";
                // string body = msg;

                var smtp = new SmtpClient
                {
                    Host ="smtp.live.com", //"smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(senderEmail, fromPassword)
                };
                //int count = this.MailQueue.Count;
                //for (int i = 0; i < count; i++)
                //{
                MailMessage mm;
                while (this.MailQueue.TryPeek(out mm))
                {
                    smtp.Send(mm);

                    while (this.MailQueue.TryDequeue(out mm))
                        break;
                    mm.Dispose();
                }
                //}
            }
            finally
            {
                if (this.MailQueue.Count > 0)
                    _sendMailTimer.Enabled = true;
            }
        }


        public void StopSendMailTimer()
        {
            _sendMailTimer.Stop();
        }
        public void StartSendMailTimer()
        {
            _sendMailTimer.Start();
        }

        internal void AddToQueue(MailMessage message)
        {
            this.MailQueue.Enqueue(message);
            _sendMailTimer.Enabled = true;

        }
    }
}
